package com.longmao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longmao.eduservice.client.VodClient;
import com.longmao.eduservice.entity.EduVideo;
import com.longmao.eduservice.mapper.EduVideoMapper;
import com.longmao.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author longmao
 * @since 2022-01-27
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private EduVideoService videoService;

    //注入删除视频的方法
    @Autowired
    private VodClient vodClient;

    @Override
    public boolean getVideoByChapterId(String chapterId) {
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("chapter_id", chapterId);
        Integer selectCount = baseMapper.selectCount(videoQueryWrapper);
        return null != selectCount && selectCount > 0;
    }

    @Override
    public boolean deleteVideoById(String videoId) {
        //先根据小节获取视频id
        EduVideo eduVideo = videoService.getById(videoId);
        //先删除视频在删除小节
        if(!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            //根据视频id 远程调用实现删除
            vodClient.deleteVodVideo(eduVideo.getVideoSourceId());
        }
        Integer result = baseMapper.deleteById(videoId);
        return null != result && result > 0;
    }

    @Override
    public boolean deleteVideoByCourseId(String courseId) {
        //根据课程id查询所有的视频id
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        //查询指定的列
        videoWrapper.select("video_source_id");
        List<EduVideo> videoList = baseMapper.selectList(videoWrapper);

        List<String> videoIds = new ArrayList<>();

        for (int i = 0; i < videoList.size(); i++) {
            EduVideo eduVideo = videoList.get(i);
            if(!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
                videoIds.add(eduVideo.getVideoSourceId());
            }
        }

        if(videoIds.size() > 0) {
            //根据多个视频id删除多个视频
            vodClient.deleteBatch(videoIds);
        }

        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        Integer result = baseMapper.delete(videoQueryWrapper);
        return null != result && result > 0;
    }
}
